local quanbian = fk.CreateSkill{
    name = "jinhs__quanbian",
}

Fk:loadTranslationTable{
  ["jinhs__quanbian"] = "权变",
  [":jinhs__quanbian"] = "出牌阶段，当你使用或打出每种花色的第一张手牌时，你可以记录此花色并摸一张牌；当你使用已记录花色的牌时，本回合“权变”失效。",

  ["@jinhs__quanbian-phase"] = "权变",
  ["@@jinhs__quanbian-turn"] = "权变 失效",

  ["$jinhs__quanbian1"] = "以退为进，俗子焉能度之。",
  ["$jinhs__quanbian2"] = "应时而变，当行权宜之计。",
}

local quanbian_spec = {
    anim_type = "drawcard",
    can_trigger = function(self, event, target, player, data)
      if target == player and player:hasSkill(quanbian.name) and player.phase == Player.Play and
        data.card.suit ~= Card.NoSuit and data:isUsingHandcard(player) then
        local card_suit = data.card.suit
        local room = player.room
        local logic = room.logic
        local current_event = logic:getCurrentEvent()
        local mark_name = "jinhs__quanbian_" .. data.card:getSuitString() .. "-phase"
        local mark = player:getMark(mark_name)
        if mark == 0 then
          logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
            local use = e.data
            if use.from == player and use.card.suit == card_suit and e.data:isUsingHandcard(player) then
              mark = e.id
              return true
            end
          end, Player.HistoryPhase)
          logic:getEventsOfScope(GameEvent.RespondCard, 1, function (e)
            local use = e.data
            if use.from == player and use.card.suit == card_suit and e.data:isUsingHandcard(player) then
              mark = (mark == 0) and e.id or math.min(e.id, mark)
              return true
            end
          end, Player.HistoryPhase)
          room:setPlayerMark(player, mark_name, mark)
        end
        return mark == current_event.id
      end
    end,
    on_use = function(self, event, target, player, data)
        player.room:addTableMark(player, "@jinhs__quanbian-phase", data.card:getSuitString(true))
        player:drawCards(1, quanbian.name)
    end,
}

quanbian:addEffect(fk.CardUsing, quanbian_spec)
quanbian:addEffect(fk.CardResponding, quanbian_spec)

quanbian:addEffect(fk.AfterCardUseDeclared, {
    can_refresh = function (self, event, target, player, data)
      return target == player and player:hasSkill(quanbian.name) and player.phase == Player.Play and
        data:isUsingHandcard(player) and table.contains(player:getTableMark("@jinhs__quanbian-phase"), data.card:getSuitString(true))
    end,
    on_refresh = function (self, event, target, player, data)
        player.room:setPlayerMark(player, "@@jinhs__quanbian-turn", 1)
        player.room:invalidateSkill(player, quanbian.name, "-turn")
    end,
})

return quanbian